package scc.project.web.interceptor.manage;

import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;
import scc.project.entity.Employee;
import scc.project.entity.vo.JsonVo;
import scc.project.util.HttpUtil;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * <h2>登陆的拦截器，如果登陆了就会往下执行</h2>
 * <dl>没有登陆的情况有两种(根据 Accept 头来判断):</dl>
 * <dt>如果使用的是JSON 请求的话则返回 JSON 到客户端</dt>
 * <dt>其余的是使用其它方式请求</dt>
 *
 * @author 陈圳佳
 *         日期：2015/6/22
 */
public class LoginInterceptor implements HandlerInterceptor {
    public static final String HEADER_ACCEPT = "Accept";

    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        Employee employee = HttpUtil.getEmp(request.getSession());
        if (employee == null) {
            String accept = request.getHeader(HEADER_ACCEPT);
            String contentType = request.getContentType();
            if (accept.contains("json") || (contentType != null && contentType.indexOf("json") > 0)) {
                response.setContentType("application/json;charset=utf-8");
                ObjectMapper mapper = new ObjectMapper();
                JsonVo jsonVo = new JsonVo();
                jsonVo.setStatus(false).setMsg("对不起你没有登陆!请登录再试").addValue("url", request.getContextPath() + "/login.html");
                mapper.writeValue(response.getWriter(), jsonVo);
            } else {
                response.sendRedirect("/login.html");
            }
            return false;
        }
        return true;
    }

    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {

    }

    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {

    }
}
